package com.utils;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import lombok.extern.slf4j.Slf4j;


import java.io.IOException;

/**
 * @author Yadasu
 * @date 2021/1/18 11:04
 */
@Slf4j
public class ShellUtils {

    public ShellUtils() {
    }

    private Connection conn;
    private static final int TIME_OUT = 1000 * 5 * 60;

    //执行shell
    private  boolean login(String ip,String username,String password) throws IOException {
        conn = new Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(username, password);
    }

    public  Integer exec(String shell,String ip,String username,String password) throws Exception {
        Integer ret = -1;
        try {
            if (login(ip, username, password)) {

                Session session = conn.openSession();
                session.execCommand(shell);
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                ret = session.getExitStatus();
                log.info("开始执行shell脚本");
            } else {
                throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return ret;
    }

//    public static void main(String[] args) throws Exception {
//        ShellUtils shellUtils=new ShellUtils();
//        System.out.println(shellUtils.login("47.111.22.109","root","Aimer123!@"));
//        System.out.println(shellUtils.exec("sh /usr/local/test/app.sh","47.111.22.109","root","Aimer123!@"));
//    }
}
